package com.i2works.smartluolong.api.controller.oauth;

import com.alibaba.fastjson.JSONObject;
import com.i2works.smartluolong.api.utils.BaseModule;
import com.i2works.smartluolong.api.utils.HttpUtils;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.common.BaseUtils;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.entity.user.UserAccountDO;
import com.i2works.smartluolong.web.entity.user.UserAccountQuery;
import com.i2works.smartluolong.web.service.user.IUserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
  * 个人接口
 * Created by liu yapeng on 2018/10/15.
 */

 @Controller
 @RequestMapping(value = "user/")
public class userOauthController extends BaseModule {
	 
	 /**
	     * 通用错误键名
	     */
	   public final static String MESSAGE_CODE = "messageCode";
	 
	   private final IUserAccountService userAccountService;

	    @Autowired
	    public userOauthController(IUserAccountService userAccountService) {
	        this.userAccountService = userAccountService;
	    }

    private final String personalUaaUrl = "https://puser.hnzwfw.gov.cn:8081";
    private final String personalWebUrl = "https://puser.hnzwfw.gov.cn:8082";
    private final String legalUaaUrl ="https://puser.hnzwfw.gov.cn:8083";//法人同个人，作为区分，实则和个人地址等效
    private final  String appId ="0000xjy1";
	private final  String appSecret ="23a50ce2-bb07-400c-a469-6d6f9f4c84d";

    /**
     * 本地登陆
     * @throws ServiceException 
     * */
    public void localLogin(String token) throws ServiceException {
 		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
    	    String userData=getBriefUser(token);
    		JSONObject userJson=JSONObject.parseObject(userData);
    		UserAccountQuery  query=new UserAccountQuery();
    		query.setUserName(userJson.getString("userName"));
    		 Integer count = userAccountService.queryCheck(query);
    		UserAccountDO userLogin =new UserAccountDO();
    		userLogin.setUserName(userJson.getString("userName"));
    		userLogin.setPhone(userJson.getString("mobile"));
    		userLogin.setEmail(userJson.getString("email"));
    		userLogin.setOpenId(userJson.getString("userId"));
    		userLogin.setCategory(Integer.valueOf(userJson.getString("category")));
    		userLogin.setPassword("123456");
    		userLogin.setStatus(1);
    		userLogin.setLoginIp(BaseUtils.getIP(request));
    		userLogin.setCreateName(userJson.getString("userName"));
    		userLogin.setUpdateName(userJson.getString("userName"));
    		if(count==0) {
    			userAccountService.saveRegisterUser(userLogin);
    		}else {
    			userAccountService.updateByPhone(userLogin);
    		}
  
    }


    /**
     *
     * app登陆
     * @param username
     * @param password
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/login")
    @ResponseBody
    public Result token(@RequestParam("username") String username,@RequestParam("password") String password) throws IOException {
    	try {
    	 String url = personalUaaUrl+"/uaa/obtainToken";
         JSONObject param = new JSONObject();
        param.put("username",username);
        param.put("password",password);
        param.put("client_id",appId);
        String data = HttpUtils.connections(url, "POST",param.toString(),"application/json");
        JSONObject json=new JSONObject();
        if(data!=null){
        	json=JSONObject.parseObject(data);
        }else{
        	 return R.error("用户名密码错误");
        }
        String token=json.getString("accessToken");
        //本地登陆系统登陆
       localLogin(token);
        //用于登录后跳转到之前网址
       UserAccountDO userLogin = new UserAccountDO();
       userLogin= userAccountService.queryLoginUser(username);
        Map<String, Object> map =new HashMap<String, Object>();
        map.put("token", token);
        map.put("userId",userLogin.getId()); 
	   return R.success(map);
       } catch (ServiceException e) {
    	   return R.error(MsgEnum.LOGIN_FAILED.getMsg());
       }
    
    }
    
    
    /**
     * 根据token查询用户基本信息
     * @param token token是使用code换取的token的全部信息
     * @return
     */
    @RequestMapping(value = "getBriefUser")
    public String getBriefUser(String token) {
        String url = personalWebUrl+"/openApi/user/getBriefUser";
        String queryString = "token="+token;//queryString是要传的参数
        String result = HttpUtils.sendGet(url,queryString);
        return result;
    }
    


}
